package com.demo.auth.controller;

import com.demo.auth.constant.ClientId;
import com.demo.auth.dao.domain.User;
import com.demo.auth.dao.service.UserService;
import com.demo.auth.entity.qo.LoginQo;
import com.demo.auth.service.AuthenticationTokenService;
import com.demo.auth.service.UsernamePasswordService;
import com.demo.starter.dto.GeneralResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.util.Assert;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录认证中心
 */
@Slf4j
@RestController
@RequestMapping("/oauth")
public class UsernamePasswordController {

    @Resource
    private TokenEndpoint tokenEndpoint;
    @Resource
    private UserService userService;
    @Resource
    private UsernamePasswordService usernamePasswordService;
    @Resource
    private AuthenticationTokenService authenticationTokenService;
    @Resource
    private ObjectMapper objectMapper;

    @PostMapping("/login")
    public GeneralResult<OAuth2AccessToken> login(@RequestBody LoginQo qo) throws HttpRequestMethodNotSupportedException,
            JsonProcessingException {

        User user = userService.lambdaQuery()
                .eq(User::getUserName, qo.getUserName())
                .eq(User::getPassword, qo.getPassword())
                .one();
        Assert.notNull(user, "user对象不能为空");
        log.info("用户信息：{}", objectMapper.writeValueAsString(user));

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                authenticationTokenService.initUsernamePasswordAuthenticationToken(ClientId.ADMIN_HIS);

        Map<String, String> parameters = new HashMap<>();
        parameters.put("grant_type", "password");
        parameters.put("client_id", ClientId.ADMIN_HIS);
        parameters.put("client_secret", "123456");
        parameters.put("username", user.getId().toString());
        parameters.put("password", user.getPassword());

        OAuth2AccessToken accessToken = tokenEndpoint.postAccessToken(usernamePasswordAuthenticationToken, parameters).getBody();
        usernamePasswordService.storeInfoToCache(user, accessToken);
        return GeneralResult.success(accessToken);
    }

    @PostMapping("/logout")
    public GeneralResult<Void> logout(@RequestHeader("userId") String userId) {
        log.info("header userId:{}", userId);
        usernamePasswordService.logout(userId);
        return GeneralResult.success();
    }
}
